/**
 *
 */
package com.jinglu.cloud.security.intercept;


import cn.hutool.core.collection.CollectionUtil;
import com.jinglu.cloud.security.config.IgnoredSecurityProperties;
import com.jinglu.cloud.security.manage.PermissionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 描述:  .<br>
 * 权限资源管理器
 * 为权限决断器提供支持
 *
 * @author zhaotengfei
 * @date 2019年11月20日
 */
@Component
public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    private final static Logger logger = LoggerFactory.getLogger(MySecurityMetadataSource.class);

    private Map<String, Collection<ConfigAttribute>> map = null;

    @Autowired
    private PermissionManager permissionManager;

    @Autowired
    private IgnoredSecurityProperties ignoredUrlsProperties;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        //Object中包含用户请求request
        String url = ((FilterInvocation) object).getRequest().getRequestURI();
        logger.info("请求鉴权URL:" + url);
        PathMatcher pathMatcher = new AntPathMatcher();
        List<String> ignoreUrls = ignoredUrlsProperties.getUrls();
        for(String ignoreUrl : ignoreUrls){
            if(pathMatcher.match(ignoreUrl,url)){
                logger.info("忽略该url鉴权");
                return null;
            }
        }

        if (permissionManager == null) {
            return null;
        }
        map = permissionManager.loadResourceDefine();
        if(CollectionUtil.isNotEmpty(map)){
            Iterator<String> iterator = map.keySet().iterator();
            while (iterator.hasNext()) {
                String resURL = iterator.next();
                if (!StringUtils.isEmpty(resURL) && pathMatcher.match(resURL, url)) {
                    logger.info("获取到相匹配的资源{}",resURL);
                    return map.get(resURL);
                }
            }
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }

    public void setPermissionManager(PermissionManager permissionManager) {
        this.permissionManager = permissionManager;
    }
}
